package com.zhc.dejingapi.utils.equipment;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhc.dejingapi.entity.QingEquipmentEntity;
import com.zhc.dejingapi.entity.QingSfcmoroutingshiftEntity;
import com.zhc.dejingapi.entity.RealtimeEntity;
import com.zhc.dejingapi.entity.SpcEntity;
import com.zhc.dejingapi.mapper.*;
import com.zhc.dejingapi.pojo.equipment.QingEqCurrentStatusParam;
import com.zhc.dejingapi.pojo.param.QingCommonBackResult;
import com.zhc.dejingapi.pojo.qingflow.QingflowApiInfo;
import com.zhc.dejingapi.pojo.qingflow.appdata.adddata.QingAddDataResultMain;
import com.zhc.dejingapi.pojo.qingflow.queryresult.QingQueryActionResultBase;
import com.zhc.dejingapi.utils.common.DateTimeUtils;
import com.zhc.dejingapi.utils.qing.QingflowAPIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class EquipmentCalUtils {

    public static EQCurrentStatusUploadUtils eqCurrentStatusUploadUtils = null;

    public static void LoadUploadUtis(QingflowApiInfo qqingflowApiInfo,
                                      QingAppfieldsMapper qingAppfieldsMapper,
                                      QingAppfieldtablevaluesMapper qingAppfieldtablevaluesMapper,
                                      JdbcTemplate mysqlJdbcTemplate) throws Exception {
        //main_id	appKey	appName	is_Delete	is_needSyn	appType
        //122	824493ic1o01	设备及时状态信息	0	1	0
        String strTableName = "qing_eqcurrentstatus";//虚拟表名，不作回写，需要修改

        //region mapContrastFields&mapContrastDetailFields

        Map<String, String> mapContrastFields = new HashMap<>();
        mapContrastFields.put("设备ID","eqId");//eqId 设备ID
        mapContrastFields.put("设备编号","eqCode");//eqCode 设备编码
        mapContrastFields.put("设备名称","eqName");//eqName 设备名称
        mapContrastFields.put("设备规格","eqStd");//eqStd 设备规格
        mapContrastFields.put("设备当前状态","eqCurrStatus");//eqCurrStatus 设备当前状态
        mapContrastFields.put("设备运行状态","eqRunStatus");//eqRunStatus 设备运行状态
        mapContrastFields.put("设备状态ID","eqRunStateId");//eqRunStateId 设备运行状态ID
        mapContrastFields.put("使用车间","useWorkShop");//useWorkShop 使用车间
        mapContrastFields.put("设备分类","eqClass");//eqClass 设备分类
        mapContrastFields.put("状态","eqStatus");//eqStatus 状态
        mapContrastFields.put("可用结束时间","eqAvailCanEndTime");//eqAvailCanEndTime 可用结束时间
        mapContrastFields.put("任务累计结束时间","eqWorkCanEndTime");//eqWorkCanEndTime 任务累计结束时间
        mapContrastFields.put("预计结束时间","eqRunCanEndTime");//eqRunCanEndTime 预计结束时间

        Map<String, String> mapContrastDetailFields = new HashMap<>();

        //endregion


        eqCurrentStatusUploadUtils = null;
        try {
            eqCurrentStatusUploadUtils = new EQCurrentStatusUploadUtils(
                    qqingflowApiInfo,
                    mysqlJdbcTemplate,
                    qingAppfieldsMapper,
                    qingAppfieldtablevaluesMapper,
                    mapContrastFields,
                    mapContrastDetailFields,
                    strTableName);
        } catch (Exception e) {
            log.error(e.getMessage() + "\n" + e.getStackTrace().toString());
            throw e;
        }

    }

    public QingCommonBackResult CalAvailTime(QingflowApiInfo qqingflowApiInfo,
                                             RealtimeMapper realtimeMapper, SpcMapper spcMapper,
                                             QingSfcmoroutingshiftMapper qingSfcmoroutingshiftMapper,
                                             JdbcTemplate mysqlJdbcTemplate,
                                             QingEquipmentEntity entity) {
        QingCommonBackResult backResult = new QingCommonBackResult();
        //122	824493ic1o01	设备及时状态信息

        QingEqCurrentStatusParam param = new QingEqCurrentStatusParam();
        param.CopyEQEntity(entity);
        QueryWrapper<RealtimeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("e_id", entity.getMainId());
        RealtimeEntity realtimeEntity = realtimeMapper.selectOne(queryWrapper);


        Date currentDateTime = new Date();
        //eqAvailCanEndTime	datetime		eqWorkCanEndTime

        //eqWorkCanEndTime	datetime		任务累计结束时间

        //eqRunCanEndTime	datetime		预计结束时间
        Date eqAvailCanEndTime = null;//eqWorkCanEndTime
        Date eqWorkCanEndTime = null;//任务累计结束时间
        Date eqRunCanEndTime = null;//预计结束时间

        //("0: 停机 1：待机 2：生产 3：报警")
        int iIOTRunStatus = 0;
        int iWorkStatus = 0;

        if (realtimeEntity == null) {
            iIOTRunStatus = -1;
        } else {
            //要判断有没有工单在做
            iIOTRunStatus = realtimeEntity.getSts();
        }

        Date orderEndTime = null;
        Date eqRunEndTime = null;
        Date orderActualStartTime = null;
        LocalDateTime localDateTime = null;


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //判断状态
        //看IOT结束时间
        QueryWrapper<SpcEntity> spcQueryWrapper = new QueryWrapper<>();
        //spcQueryWrapper.orderByDesc("time");
        spcQueryWrapper.eq("e_id", param.getEqId())
                .orderByDesc("time")
                .last("LIMIT 1");
        SpcEntity spcEntity = spcMapper.selectOne(spcQueryWrapper);

        QueryWrapper<QingSfcmoroutingshiftEntity> sfcRunEntityQueryWrapper = new QueryWrapper<>();
        sfcRunEntityQueryWrapper.last(" appKey='7nhiubrg1k02' \n" +
                "and workTaskState='已启动'\n" +
                "and (eqId=" + param.getEqId() + " or  eqCode='" + param.getEqCode() + "' )\n")
                .orderByDesc("planBeginDate")
                .last("LIMIT 1");


        QingSfcmoroutingshiftEntity sfcRunEntity = qingSfcmoroutingshiftMapper.selectOne(sfcRunEntityQueryWrapper);


        //需要运行的工单

        QueryWrapper<QingSfcmoroutingshiftEntity> sfcNeeRunEntityQueryWrapper = new QueryWrapper<>();
        sfcNeeRunEntityQueryWrapper.last(" appKey='7nhiubrg1k02' \n" +
                "and workTaskState='未开始'\n" +
                "and (eqId=" + param.getEqId() + " or  eqCode='" + param.getEqCode() + "' )\n");
        sfcNeeRunEntityQueryWrapper.orderByDesc("planBeginDate");
        QingSfcmoroutingshiftEntity sfcNeedRunEntity = qingSfcmoroutingshiftMapper.selectOne(sfcRunEntityQueryWrapper.last("LIMIT 1"));


        //获取正在生产的这个工单
        if (sfcRunEntity == null || spcEntity == null) {
            //没有工单正在启动
            //就需要看工单的最后预计时间
            if (sfcNeedRunEntity == null) {
                //eqAvailCanEndTime	datetime		eqWorkCanEndTime
                eqAvailCanEndTime = currentDateTime;
                //eqWorkCanEndTime	datetime		任务累计结束时间
                eqWorkCanEndTime = currentDateTime;
                //eqRunCanEndTime	datetime		预计结束时间
                eqRunCanEndTime = currentDateTime;
            } else {
                if (sfcNeedRunEntity.getEstimatedEndTime() == null) {
                    localDateTime = sfcNeedRunEntity.getPlanEndDate();
                } else {
                    localDateTime = sfcNeedRunEntity.getEstimatedEndTime();
                }

                //根据最后一个工单的结束时间来计算
                eqAvailCanEndTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                eqWorkCanEndTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
                eqRunCanEndTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());


            }
            if (eqAvailCanEndTime.compareTo(currentDateTime) < 0) {
                eqAvailCanEndTime = currentDateTime;
                eqWorkCanEndTime = currentDateTime;
                eqRunCanEndTime = currentDateTime;
            }

        } else {
            //如果有工单，则计算一下是提前还是结束
            //if(spcEntity==null){//正在运行的结果没有，则根据工单来计划
            //
            //}

            String strSql = "SELECT moldAvailCavityNum\n" +
                    "from qing_mold\n" +
                    "where moldCode=?";
            int iAvailCavityNum = mysqlJdbcTemplate.queryForObject(strSql, new Object[]{sfcRunEntity.getMoldCode()}, Integer.class);

            if (iAvailCavityNum == 0) {
                iAvailCavityNum = 1;
            }


            int iTaskQty = sfcRunEntity.getPlanQty();
            String strVal = spcEntity.getEcyct();
            Double dCycleTime = Double.parseDouble(strVal);

            //Double dCycleTime=spcEntity.getEcyct();

            //int iRunnedQty=spcEntity.getCycn();
            strVal = spcEntity.getEcyct();
            int iRunnedQty = Integer.parseInt(strVal);

            int iNeedSecond = 0;
            //判断还需要多少时间完成
            if (iTaskQty > iRunnedQty) {
                iNeedSecond = (int) ((iTaskQty - iRunnedQty) * dCycleTime) / iAvailCavityNum;
            }

            if (sfcRunEntity.getActualEndTime() == null) {
                orderActualStartTime = new Date();
            } else {
                try {
                    orderActualStartTime = Date.from(sfcRunEntity.getActualEndTime().atZone(ZoneId.systemDefault()).toInstant());

                    if (orderActualStartTime.compareTo(currentDateTime) < 0) {
                        orderActualStartTime = currentDateTime;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    orderActualStartTime = new Date();
                }
            }
            if (iNeedSecond > 0) {
                orderActualStartTime = DateTimeUtils.AddSecond(orderActualStartTime, iNeedSecond);
                currentDateTime = DateTimeUtils.AddSecond(currentDateTime, iNeedSecond);
            }
            eqAvailCanEndTime = orderActualStartTime; //设备可用时间
            eqWorkCanEndTime = orderActualStartTime;//任务累计结束时间
            eqRunCanEndTime = currentDateTime; //设备运行结束时间

        }


        if (realtimeEntity == null) {
            if (sfcRunEntity == null) {

                if (sfcNeedRunEntity == null) {
                    iWorkStatus = 0;
                } else {
                    iWorkStatus = 1;
                }
            } else {

                iWorkStatus = 2;
            }
            param = setEQSTatus(param, iWorkStatus);
        } else {
            param = setEQSTatus(param, iIOTRunStatus);
        }
        //eqAvailCanEndTime=orderActualStartTime; //设备可用时间
        param.setEqAvailCanEndTime(sdf.format(eqAvailCanEndTime));
        //eqWorkCanEndTime= orderActualStartTime;//任务累计结束时间
        param.setEqWorkCanEndTime(sdf.format(eqWorkCanEndTime));
        //eqRunCanEndTime=currentDateTime; //设备运行结束时间
        param.setEqRunCanEndTime(sdf.format(eqRunCanEndTime));

        //上传任务

        return UploadToQing(qqingflowApiInfo, param, mysqlJdbcTemplate);
    }

    public QingEqCurrentStatusParam setEQSTatus(QingEqCurrentStatusParam soureParam, int iRunStatus) {
        QingEqCurrentStatusParam param = new QingEqCurrentStatusParam();
        param = soureParam;
        //("0: 停机 1：待机 2：生产 3：报警")
        param.setEqRunStateId(iRunStatus);
        switch (iRunStatus) {
            case 0:
                param.setEqRunStatus("停机");
                break;
            case 1:
                param.setEqRunStatus("待机");
                break;
            case 2:
                param.setEqRunStatus("生产");
                break;
            case 3:
                param.setEqRunStatus("报警");
                break;
        }

        return param;

    }


    public QingCommonBackResult UploadToQing(QingflowApiInfo qqingflowApiInfo, QingEqCurrentStatusParam param, JdbcTemplate mysqlJdbcTemplate) {
        QingCommonBackResult commonBackResult = new QingCommonBackResult();
        //判断有没有这一行。
        String qingApplyId = "";
        String strSql = "SELECT Count(*) from qing_eqcurrentstatus where eqId=?";
        Integer iHaveCount = mysqlJdbcTemplate.queryForObject(strSql, new Object[]{param.getEqId()}, Integer.class);
        if (iHaveCount >0) {
            strSql = "SELECT qingApplyId from qing_eqcurrentstatus where eqId=?";
            qingApplyId = mysqlJdbcTemplate.queryForObject(strSql, new Object[]{param.getEqId()}, String.class);
        }


        if (qingApplyId == null || qingApplyId.isEmpty()) {
            //增加
            try {

                QingAddDataResultMain resultMain = eqCurrentStatusUploadUtils.AddEntity(param);
                //region 处理返回结果
                if (resultMain == null) {

                    commonBackResult.setErrCode(-10015);
                    commonBackResult.setErrMsg("服务器返回内容为空！");

                } else {
                    if (resultMain.getErrCode() == 0) {
                        commonBackResult.setErrCode(resultMain.getErrCode());
                        commonBackResult.setErrMsg("提交成功！");
                        commonBackResult.setBackValue(resultMain.getResult().getRequestId());

                        //获取查询值的结果
                        String strRequestId = resultMain.getResult().getRequestId();
                        try {
                            Thread.sleep(500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        QingQueryActionResultBase actionResultBase = QingflowAPIUtils.GetRequestResult(qqingflowApiInfo, strRequestId);
                        if (actionResultBase == null) {
                            commonBackResult.setErrCode(-10066);
                            commonBackResult.setErrMsg("提交成功：获取提交结果的内容为空！");

                        } else {
                            if (actionResultBase.getErrorCode() == 0) {

                                commonBackResult.setErrCode(0);
                                commonBackResult.setErrMsg("提交成功！");
                                String strValue = actionResultBase.getResult();
                                if (strValue == null || strValue.isEmpty()) {

                                } else {
                                    Long lValue = Long.parseLong(actionResultBase.getResult());
                                    commonBackResult.setBackLongValue(lValue);
                                    strSql="UPDATE  qing_eqcurrentstatus set qingApplyId=? where eqId=?";
                                    mysqlJdbcTemplate.update(strSql,new Object[]{lValue,param.getEqId()});
                                }

                            } else {

                                commonBackResult.setErrCode(actionResultBase.getErrorCode());
                                commonBackResult.setErrMsg(actionResultBase.getMessage());

                            }
                        }

                    } else {
                        commonBackResult.setErrCode(resultMain.getErrCode());
                        commonBackResult.setErrMsg(resultMain.getErrMsg());

                    }

                }
                //endregion
            } catch (Exception e) {
                e.printStackTrace();
                commonBackResult.setErrCode(-10012);
                commonBackResult.setErrMsg("出错：" + e.getMessage() + "\n" + e.getStackTrace());
            }
        } else {
            //修改
            try {
                Long lqingApplyId = Long.parseLong(qingApplyId);
                param.setQingApplyId(lqingApplyId);
                try {

                    QingAddDataResultMain resultMain = eqCurrentStatusUploadUtils.UpdEntity(param, "A");
                    //region 处理返回结果
                    if (resultMain == null) {

                        commonBackResult.setErrCode(-10015);
                        commonBackResult.setErrMsg("服务器返回内容为空！");

                    } else {
                        if (resultMain.getErrCode() == 0) {
                            commonBackResult.setErrCode(resultMain.getErrCode());
                            commonBackResult.setErrMsg("提交成功！");
                            commonBackResult.setBackValue(resultMain.getResult().getRequestId());
                            //获取查询值的结果
                            String strRequestId = resultMain.getResult().getRequestId();
                            try {
                                Thread.sleep(500);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            QingQueryActionResultBase actionResultBase = QingflowAPIUtils.GetRequestResult(qqingflowApiInfo, strRequestId);
                            if (actionResultBase == null) {
                                commonBackResult.setErrCode(-10066);
                                commonBackResult.setErrMsg("提交成功：获取提交结果的内容为空！");

                            } else {
                                if (actionResultBase.getErrorCode() == 0) {

                                    commonBackResult.setErrCode(0);
                                    commonBackResult.setErrMsg("提交成功！");
                                    String strValue = actionResultBase.getResult();
                                    if (strValue == null || strValue.isEmpty()) {

                                    } else {
                                        Long lValue = Long.parseLong(actionResultBase.getResult());
                                        commonBackResult.setBackLongValue(lValue);
                                    }

                                } else {

                                    commonBackResult.setErrCode(actionResultBase.getErrorCode());
                                    commonBackResult.setErrMsg(actionResultBase.getMessage());

                                }
                            }

                        } else {
                            commonBackResult.setErrCode(resultMain.getErrCode());
                            commonBackResult.setErrMsg(resultMain.getErrMsg());

                        }

                    }
                    //endregion
                } catch (Exception e) {
                    e.printStackTrace();
                    commonBackResult.setErrCode(-10012);
                    commonBackResult.setErrMsg("出错：" + e.getMessage() + "\n" + e.getStackTrace());
                }

            } catch (Exception e) {
                e.printStackTrace();
                commonBackResult.setErrCode(-10012);
                commonBackResult.setErrMsg("出错：" + e.getMessage() + "\n" + e.getStackTrace());
            }


        }
        try{
            param.setErrCode(commonBackResult.getErrCode());
            param.setErrMsg(commonBackResult.getErrMsg());
            param.setLastRequestId(commonBackResult.getBackValue());
            param.setQingApplyId(commonBackResult.getBackLongValue());
            param.SaveToDB(mysqlJdbcTemplate);
        }
        catch (Exception e){
            e.printStackTrace();
        }


        return commonBackResult;
    }

}
